#!/bin/bash
export version=1.0.0
export serverDir=`pwd`
export serverName=package_demo-${version}.jar
export pidFileName=package_demo.pid

#java env
#export JAVA_HOME=/usr/java/jdk1.8.0_45
export JVM_OPTS="-Xms4g -Xmx4g -Xmn2g -Xss256k  -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=128M -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=92 -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSParallelInitialMarkEnabled -XX:+CMSScavengeBeforeRemark -XX:+DisableExplicitGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:./gc/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=32 -XX:GCLogFileSize=64M -XX:+HeapDumpOnOutOfMemoryError  -XX:HeapDumpPath=./oom"

export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"
export isPrintLogo=1

#打印logo
function printLogo(){
    if [ ${isPrintLogo} -eq 0 ]
    then
        s=0.1
        echo ""
        echo "          ####  #####  ####  #####    ##    ####  ###### "

        echo "            __  __     ______     __         __  __      "
        sleep ${s}
        echo "           /\ \_\ \   /\  __ \   /\ \       /\ \/ /      "
        sleep ${s}
        echo "           \ \  __ \  \ \  __ \  \ \ \____  \ \  _'-.    "
        sleep ${s}
        echo "            \ \_\ \_\  \ \_\ \_\  \ \_____\  \ \_\ \_\   "
        sleep ${s}
        echo "             \/_/\/_/   \/_/\/_/   \/_____/   \/_/\/_/   "
        sleep ${s}
        echo "         ####    #    ####  #    # #    #  ####  ######  "
        sleep ${s}
        echo ""
        echo "    :: halk extract ::   (v.RELEASE)"
    fi
}

#检查进程是否运行
function checkExist(){
  pid=`ps -ef|grep $serverName|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid}" ]; then
    return 1
  else
    return 0
  fi
}

#停止
function stop(){
   #is_exist
  pidf=$(cat ${serverDir}/${pidFileName})
  if [ -n "${pidf}" ]; then
      echo ">>> begin kill pid=${pidf} <<<"
      kill ${pidf}
      rm -rf ${serverDir}/${pidFileName}
      sleep 2
  fi
  checkExist
  if [ $? -eq 0 ]; then
    echo ">>> begin kill -9 pid=${pid} <<<"
    kill -9 ${pid}
    sleep 2
    echo ">>> ${serverName} process stopped <<<"
  else
    echo ">>> ${serverName} is not running <<<"
  fi
}

#启动
function start(){
  checkExist
  if [ $? -eq 0 ]; then
      echo ">>> ${serverName} is already running pid=${pid} <<<"
  else
    echo ">>> starting $serverName... <<<"
    if [ ! -d "gc" ]; then
       mkdir "gc"
    fi
    if [ ! -d "oom" ]; then
       mkdir "oom"
    fi
    exec nohup java ${JVM_OPTS} -jar ${serverDir}/${serverName} > /dev/null 2>stderr &
    echo $! > ${pidFileName}
    echo ">>> start ${serverName} success pid=$!"
    printLogo
  fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo "    ---usage: $0 [start]|[stop]|[restart]"
       ;;
esac
